import json
from rest_framework import serializers

from users.models import User
from .models import Problem, Label, Answer, ProblemLabelRelation, ChildAnswer, UsreAnswerLikesRelation, \
    UsreProblemLikesRelation
from users.serializers import UserPartInfoSerializer





class AuthorNameSerializer(serializers.ModelSerializer):
    nickname = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('nickname', 'id')


class ChildAnswerSerializer(serializers.ModelSerializer):
    """子评论"""
    child_author = AuthorNameSerializer()

    # answer_id = serializers.IntegerField(read_only=True)

    class Meta:
        model = ChildAnswer
        fields = ('child_content', 'answer_id', 'child_author')

    # def create(self, validated_data):
    #     data = super().create(validated_data)
    #     ChildAnswer.objects.craete()


class AnswerSerializer(serializers.ModelSerializer):
    """评论"""

    childanswer_set = ChildAnswerSerializer(many=True)
    answer_author = serializers.SlugRelatedField(label='作者', read_only=True, slug_field='nickname')

    class Meta:
        model = Answer
        fields = '__all__'


class ProblemLabelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = '__all__'


class DiscussionSerializer(serializers.ModelSerializer):
    """问题"""
    # Answer_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    # Label_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    # author = UserDetailSerializer('username')
    author = serializers.SlugRelatedField(label='作者', read_only=True, slug_field='nickname')

    # label_context = Problem.objects.get(id=1).label_set.all()
    # a = Answer.objects.get(id=id)
    # b = Label.objects.get()
    label_set = ProblemLabelSerializer(many=True)
    answer_set = AnswerSerializer(many=True)

    class Meta:
        model = Problem
        fields = (
            'id', 'title', 'create_time', 'browse', 'awesome', 'author', 'reply', 'content', 'label_set', 'answer_set')


class UsreProblemLikesRelationSerializer(serializers.ModelSerializer):
    """问题点赞关系表"""
    # id = serializers.IntegerField(label='ID')
    # Problem = DiscussionSerializer()
    # User = UserPartInfoSerializer()
    is_value = serializers.IntegerField(default=0, label='收藏')

    class Meta:
        model = UsreProblemLikesRelation
        fields = '__all__'
